package com.withoutwords.ui;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.withoutwords.R;
import com.withoutwords.engine.Game;
import com.withoutwords.engine.GameController;
import com.withoutwords.engine.MyInfo;
import com.withoutwords.engine.comminication.CommunicationManager;
import com.withoutwords.engine.comminication.IServerResultListener;
import com.withoutwords.engine.comminication.ServerRequests;
import com.withoutwords.engine.settings.Settings;
import com.withoutwords.engine.social.ISocialNetworkController;
import com.withoutwords.engine.social.SocialEngine;
import com.withoutwords.engine.social.SocialUser;
import com.withoutwords.engine.social.SocialNetwork;
import com.withoutwords.engine.social.listeners.ISocialFriendListListener;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.Toast;

public class CreateGameActivity extends BaseActivity implements
		OnClickListener, ISocialFriendListListener, IServerResultListener {

	ISocialNetworkController fbController;
	Handler uiHandler;
	Game game;
	ArrayList<SocialUser> friendList;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.creategame);

		Button btn = (Button) findViewById(R.id.btnStartGame);
		btn.setOnClickListener(this);
		btn.setEnabled(false);
		fbController = SocialEngine.getSocialEngine()
				.getSocialNetworkController(SocialNetwork.Facebook);
		fbController.readFriendList(this, true);

		uiHandler = new Handler();

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnStartGame: {
			game = new Game();
			ListView lv = (ListView) findViewById(R.id.lstFriends);
			if (lv != null) {
				long[] itemIds = lv.getCheckItemIds();
				for (int i = 0; i < itemIds.length; i++) {
					game.addPlayer(friendList.get((int) itemIds[i]));
				}
			}
			CheckBox cbPrivate = (CheckBox) findViewById(R.id.chckPrivate);
			if (cbPrivate != null) {
				game.setPrivateGame(cbPrivate.isChecked());
			}
			MyInfo me = Settings.getInstance().getMyInfo();
			if (me != null) {
				game.setGameOwner(me.getSocialUser());
			}
			// game.putpl
			GameController.getInstance().createGame(game);
			// startActivity(new Intent(this,StartRoundActivity.class));
			break;
		}
		}

	}

	@Override
	public void onFriendListRecieved(final ArrayList<SocialUser> friendlist) {

		this.friendList = friendlist;
		/*
		 * Bundle data = new Bundle(); data.putSerializable("friendlist",
		 * friendlist);
		 */
		Bundle bundle = new Bundle();
		JSONArray arrayJson = new JSONArray();
		for (int i = 0; i < friendlist.size(); i++) {
			try {
				arrayJson.put(i, friendlist.get(i).toJSON());
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		JSONObject obj = new JSONObject();
		try {
			obj.put(CommunicationManager.usersCode, arrayJson);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String objStr = obj.toString();
		bundle.putString(CommunicationManager.usersCode, objStr);

		
		  CommunicationManager.getCommnuicationManager().request(ServerRequests.
		  getRegisteredUser, bundle, this);
		 
		// temp until getregistered users work
		uiHandler.post(new Runnable() {

			@Override
			public void run() {
				updateListWithFriends(friendlist);

			}
		});

	}

	@Override
	public void onError(final String Error) {

		uiHandler.post(new Runnable() {

			@Override
			public void run() {
				String Msg = "General Error";
				if (Error != null)
					Msg = Error;
				// TODO Auto-generated method stub
				Toast.makeText(CreateGameActivity.this, Msg, 1000);
			}
		});
	}

	void updateListWithFriends(ArrayList<SocialUser> friendlist) {
		this.friendList = friendlist;
		ListView lv = (ListView) findViewById(R.id.lstFriends);
		if (lv != null && friendlist != null) {
			lv.setAdapter(new ArrayAdapter<SocialUser>(CreateGameActivity.this,
					android.R.layout.simple_list_item_multiple_choice,
					friendlist));// (ArrayList<SocialUser>)
									// response.get("friendList")));
			lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
			lv.invalidate();
			Button btn = (Button) findViewById(R.id.btnStartGame);
			// btn.setOnClickListener(this);
			btn.setEnabled(true);
		}
	}

	@Override
	public void onRequestSucceed(ServerRequests serverRequest,
			final Bundle response) {
		switch (serverRequest) {
		case getRegisteredUser:
			uiHandler.post(new Runnable() {

				@Override
				public void run() {
					updateListWithFriends((ArrayList<SocialUser>) response
							.get(CommunicationManager.usersCode));

				}
			});
			break;

		default:
			break;
		}

	}

	@Override
	public void onRequestFailed(ServerRequests serverRequest, final String error) {
		uiHandler.post(new Runnable() {

			@Override
			public void run() {
				String Msg = "General Error";
				if (error != null)
					Msg = error;
				// TODO Auto-generated method stub
				Toast.makeText(CreateGameActivity.this, Msg, 1000);
			}
		});
	}

}
